import { defineComponent, ref, Transition, PropType } from 'vue'
import { Moment } from 'moment'
import useMemo from '../_util/hooks/useMemo'
import { castArray } from '../_util/_'

import Calendar from './index'

export default defineComponent({
  name: 'x-range-calendar',
  props: {
    value: Array as PropType<Moment[]>,
    disabledDate: Function as PropType<(date: Moment) => boolean>,
    onSelect: Function as PropType<(date: Moment[]) => void>
  },
  emits: ['update:value', 'change'],
  setup(props, { emit }) {
    const valueRef = useMemo(() => castArray(props.value))
    const hoverValueRef = ref([])

    function onHover(date: Moment) {
      if (valueRef.value.length == 1) {
        hoverValueRef.value = [valueRef.value[0], date].sort((a, b) => +a - +b)
      }
    }
    function onSelect(date: Moment) {
      let val = valueRef.value
      if (val.length == 1) {
        val[1] = date.clone()
        val.sort((a, b) => +a - +b)
        hoverValueRef.value = []
        emit('update:value', [...val])
      } else {
        val = valueRef.value = [date.clone()]
      }

      emit('change', [...val])

      if (val[0] && val[1]) {
        props.onSelect?.(val)
      }
    }

    return () => {
      const calendarProps = {
        range: hoverValueRef.value.length ? hoverValueRef.value : valueRef.value,
        disabledDate: props.disabledDate,
        onHover,
        onSelect
      }
      return <Calendar {...calendarProps}></Calendar>
    }
  }
})
